package com.zzgele.qmzb.api.web;

import com.alibaba.boot.dubbo.annotation.DubboConsumer;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zzgele.qmzb.api.core.Constants;
import com.zzgele.qmzb.api.core.Result;
import com.zzgele.qmzb.api.core.ResultGenerator;
import com.zzgele.qmzb.api.model.Config;
import com.zzgele.qmzb.api.model.User;
import com.zzgele.qmzb.api.service.ConfigService;
import com.zzgele.qmzb.api.service.UserService;
import com.zzgele.qmzb.api.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;

/**
 * Created by Martin on 2017-07-28.
 */
@RestController
@RequestMapping("/robot")
public class RobotController {
    private final Logger logger = LoggerFactory.getLogger(RobotController.class);
    @DubboConsumer
    private UserService userService;
    @DubboConsumer
    private ConfigService configService;

    //TODO:转入后台管理
    @PostMapping("/creates")
    public Result createRobots(Integer number) {
        //int number = 100;
        //TODO:转入缓存Redis
        Config config = configService.findById(Constants.CONFIG_KEY_ROBOT_COUNT);
        int start = Integer.valueOf(config.getValue());
        number = number+start;

        int created = 0;
        for (int i=start; i<number; i++) {
            boolean ret = createRobot(String.valueOf(i));
            if(ret) {
                created++;
            } else {
                break;
            }
        }
        config.setValue(String.valueOf(start+created));
        configService.update(config);

        HashMap hashMap = new HashMap();
        hashMap.put("created", created);
        return ResultGenerator.genSuccessResult(hashMap);
    }

    private Boolean createRobot(String no) {
        //检测用户手机号是否已注册
        String mobile = "x3012345678";
        mobile = mobile.substring(0, mobile.length() - no.length())
                .concat(no);
        logger.info("mobile:{}", mobile);

        User user = userService.findBy("mobile", mobile);
        //该手机号未注册
        if (user == null) {
            user = new User();
            user.setMobile(mobile);
            user.setNickName("");
            user.setBirth("");
            user.setProvinceId(0);
            user.setCityId(0);
            user.setAccountStatus(1);
            user.setAuthenticationStatus(0);
            user.setClientType(Constants.CLIENT_TYPE_UNKNOWN);
            user.setCreateTime(DateUtil.getCurUnixTimeStampInt());
            user.setDiamond(new BigDecimal(0));
            user.setDiamondRecharge(new BigDecimal(0));
            user.setHotDesc(0);
            user.setIcon("");
            user.setGender(0);
            user.setHeight(0);
            user.setIdCard("");
            user.setLevel(Constants.USER_LEVEL_DEF);
            user.setPayPass("");
            user.setPid(0);
            user.setUserType(Constants.USER_TYPE_ROBOT);
            user.setPraise(0);
            user.setProfit(new BigDecimal(0));
            user.setProfitTotal(new BigDecimal(0));
            user.setPushStatus(Constants.USER_PUSH_STATUS_SLIENT);
            user.setRealName("");
            user.setRecommendType(Constants.USER_RECOMMEND_TYPE_NO);
            user.setSign("");
            user.setSpend(0);
            user.setTicket(new BigDecimal(0));
            user.setTicketTotal(new BigDecimal(0));
            user.setLastLoginTime(DateUtil.getCurUnixTimeStampInt());
            user.setNumber(0L);
            user.setTotalLoginCount(0);
            user.setTotalOnlineTime(0);
            user.setToken(StringUtil.getLoginToken());
            user.setImAccid("");
            user.setImToken("");
            userService.save(user);

            //logger.info("{}", user);

            //TODO:靓号预生成-取值
            Long max=userService.getMaxNumber();
            user.setNumber(UserUtil.getNumberById(user.getId(),max));

            //设置临时昵称
            String nickName = RobotUtil.getRandomRobotName();
            user.setNickName(nickName);

            //创建网易IM帐号
            String accid = UserUtil.getImAccid();
            //扩展字段
            String props = "";
            //HashMap propsMap = new HashMap();
            //propsMap.put("uid", user.getId());
            //propsMap.put("level", Constants.USER_LEVEL_DEF);
            //props = JSON.toJSONString(propsMap);

            String resIm = NeteaseImUtil.createUser(accid, user.getNickName(), props, user.getIcon());
            if(StringUtil.isEmpty(resIm)) {
                logger.warn("创建更新IM帐号失败：IM服务器异常");
                return false;
            }
            JSONObject jsonObjIm = JSON.parseObject(resIm);
            Integer codeIm = jsonObjIm.getInteger("code");
            if (!codeIm.equals(200)) {
                String errorDesc = jsonObjIm.getString("desc");
                logger.warn("创建IM帐号失败：IM服务器异常({}):{}", codeIm, errorDesc);
                return false;
            }

            JSONObject objectIm = jsonObjIm.getJSONObject("info");

            //保存IM相关信息
            String imAccid = objectIm.getString("accid");
            //String imName = objectIm.getString("name");
            String imToken = objectIm.getString("token");

            user.setImAccid(imAccid);
            user.setImToken(imToken);
            userService.update(user);

            //更新用户信息
            JSONObject object = new JSONObject();
            JSONObject data = new JSONObject();
            data.put("user_id", user.getId()); //用户UID
            data.put("number", user.getNumber()); //直播号
            data.put("city", "火星"); //城市
            //data.put("height", user.getHeight()); //身高
            // TODO: 随机等级、收到、送出
            data.put("level", user.getLevel());
            data.put("ticket", 0); //收到票数
            data.put("spend", 0); //花费钻数
            data.put("attention", 0); //关注数
            data.put("fans", 0); //粉丝数
            object.put("user_info", data);
            String ext = object.toJSONString();

            resIm = NeteaseImUtil.updateUinfo(accid, user.getNickName(), user.getIcon(), user.getSign(),
                    user.getBirth(), user.getGender(), ext);
            if(StringUtil.isEmpty(resIm)) {
                logger.warn("更新IM帐号失败：IM服务器异常");
                return false;
            }
            jsonObjIm = JSON.parseObject(resIm);
            codeIm = jsonObjIm.getInteger("code");
            if (!codeIm.equals(200)) {
                String errorDesc = jsonObjIm.getString("desc");
                logger.warn("更新IM帐号失败：IM服务器异常({}):{}", codeIm, errorDesc);
                return false;
            }

            return true;
        }
        return false;
    }
}
